<template>
	<div >
		<div class="mains">
		<Bread>
			<template v-slot:title>
				<el-breadcrumb-item v-for="(item, index) in titleList" :key="index">
					{{ item }}</el-breadcrumb-item
				>
			</template>
		</Bread>
			<el-button type="info" class="btnBlack" round @click="black">返回</el-button>
		</div>

		<el-card>
			
			<el-alert
				title="添加商品信息"
				type="info"
				show-icon
				center
				:closable="false"
			>
			</el-alert>
			<!-- 步骤条 -->
			<el-steps
				:space="200"
				:active="activeIndex - 0"
				finish-status="success"
				align-center
			>
				<el-step title="基本信息"></el-step>
				<el-step title="商品参数"></el-step>
				<el-step title="商品属性"></el-step>
				<el-step title="商品图片"></el-step>
				<el-step title="商品内容"></el-step>
				<el-step title="完成"></el-step>
			</el-steps>
			<!-- 验证表单 -->
			<el-form
				:model="ruleForm"
				:rules="rules"
				ref="ruleForm"
				label-width="100px"
				class="demo-ruleForm"
				label-position="top"
			>
				<!-- tab切换栏 -->
				<el-tabs
					tab-position="left"
					v-model="activeIndex"
					:before-leave="beforeTab"
					@tab-click="tabClick"
				>
					<!-- 基本信息 -->
					<el-tab-pane label="基本信息" name="0">
						<el-form-item label="商品名称" prop="goods_name">
							<el-input v-model="ruleForm.goods_name"></el-input>
						</el-form-item>
						<el-form-item label="商品价格" prop="goods_price">
							<el-input v-model="ruleForm.goods_price"></el-input>
						</el-form-item>
						<el-form-item label="商品重量" prop="goods_weight">
							<el-input v-model="ruleForm.goods_weight"></el-input>
						</el-form-item>
						<el-form-item label="商品数量" prop="goods_number">
							<el-input v-model="ruleForm.goods_number"></el-input>
						</el-form-item>
						<el-form-item label="商品分类" prop="goods_cat">
							<el-cascader
								v-model="ruleForm.goods_cat"
								:options="list"
								:props="addShop"
								@change="handleChange"
								:show-all-levels="false"
							></el-cascader>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品参数" name="1">
						<el-form-item v-for="item in CategoriesData" :key="item.attr_id">
							{{ item.attr_name }}
							<el-checkbox-group v-model="item.attr_vals">
								<el-checkbox
									v-for="(item, index) in item.attr_vals"
									:key="index"
									:label="item"
									border
								>
								</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品属性" name="2">
						<el-form-item
							v-for="item in staticList"
							:key="item.attr_id"
							:label="item.attr_name"
						>
							<el-input v-model="item.attr_vals"></el-input>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品图片" name="3">
						<el-upload
							class="upload-demo"
							action="http://150.158.92.60:9090/api/private/v1/upload"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							list-type="picture"
							:headers="{
								Authorization: token
							}"
							:file-list="fileList"
							:on-success="handleSuccess"

						>
							<el-button size="small" type="primary">点击上传</el-button>
							<!-- <div slot="tip" class="el-upload__tip">
								只能上传jpg/png文件，且不超过500kb
							</div> -->
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="商品内容" name="4">
						<quill-editor
							v-model="ruleForm.goods_introduce"
							ref="myQuillEditor"
							:options="editorOption"
							@blur="onEditorBlur($event)"
							@focus="onEditorFocus($event)"
							@ready="onEditorReady($event)"
						>
						</quill-editor>
						<el-row class="btn-top">
							<el-button type="primary" @click="add">添加商品</el-button>
						</el-row>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</el-card>
		<!-- 图片预览 -->

		<el-dialog
			title="图片预览"
			:visible.sync="dialogVisible"
			width="50%"
			show-close
			:lose="closed"
		>
			<img :src="urlImage" alt="" class="previewImg" />
		</el-dialog>
	</div>
</template>

<script>
import Bread from '../../components/Bread.vue'
import _ from 'lodash'
export default {
	name: 'AddShoping',
	components: {
		Bread,
	},
	data() {
		return {
			content: '',
			editorOption: {},
			dialogVisible: false,
			urlImage: '',
			fileList: [],
			staticList: [],
			titleList: ['商品管理', '添加商品'],
			activeIndex: 0,
			list: [],
			selected: [],
			CategoriesData: [],
			addShop: {
				expandTrigger: 'hover',
				label: 'cat_name',
				value: 'cat_id',
				children: 'children',
			},
			ruleForm: {
				goods_cat: [],
				goods_name: '',
				goods_price: '',
				goods_weight: '',
				goods_number: '',
				pics: [],
				goods_introduce: '',
				attrs: [],
			},
			rules: {
				goods_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
				goods_price: [{ required: true, message: '不能为空', trigger: 'blur' }],
				goods_weight: [
					{ required: true, message: '不能为空', trigger: 'blur' },
				],
				goods_number: [
					{ required: true, message: '不能为空', trigger: 'blur' },
				],
				goods_cat: [{ required: true, message: '不能为空', trigger: 'blur' }],
			},
		}
	},
	computed:{
		token:{
			get(){
				return	sessionStorage.getItem('token')
			}
		}
	},
	methods: {
		// 返回商品列表
		black(){
			this.$router.replace({
				name:'goods'
			})
		},
	
		// 添加商品按钮
		add() {
			this.$refs.ruleForm.validate(boolean => {
				if (!boolean) {
					this.$message.error('添加商品失败！')
					return
				} else {
					let forms = _.clone(this.ruleForm)
					forms.goods_cat = forms.goods_cat.join(',')
					this.CategoriesData.forEach(item => {
						let newInfo = {
							attr_id: item.attr_id,
							attr_value: item.attr_vals.join(' '),
						}
						this.ruleForm.attrs.push(newInfo)
					})
					this.staticList.forEach(item => {
						let newInfo = {
							attr_id: item.attr_id,
							attr_value: item.attr_vals,
						}
						this.ruleForm.attrs.push(newInfo)
					})
					forms.attrs = this.ruleForm.attrs					
				this.$http.post('/goods',
					forms
				).then(res => {

				let {meta} = res.data

					if(meta.status != 201){
						this.$message.error(meta.msg)
						return
					}
					this.$message({
						type:'success',
						message:meta.msg
					})
					this.$router.push({
						name:'goods'
					})
				}).catch(error => {
					console.log(error.message)
					
				})
					
				}
			})
		},
		onEditorReady() {},
		onEditorFocus() {},
		onEditorBlur() {},
		//预览图片对话框关闭
		closed() {
			this.dialogVisible = false
		},
		// 图片上传成功

		handleSuccess(response) {		
			this.ruleForm.pics.push(response.data.tmp_path)	
		},
		// 预览图片
		handlePreview(file) {		
				this.dialogVisible = true
			this.urlImage = file.response.data.url
			
		},
		//	关闭图片
		handleRemove(file) {
			let count = this.ruleForm.pics.findIndex(item => {
				item == file.response.data.tmp_path
			})
			this.ruleForm.pics.splice(count, 1)
		},
		// tab被选中的时候
		tabClick() {
			// 选中第二个 tab栏目
			if (this.activeIndex == '1') {
				this.getCategoriesData()
			}
			//选中第三个tab栏目
			if (this.activeIndex == '2') {
				this.$http
					.get(`categories/${this.ruleForm.goods_cat[2]}/attributes`, {
						params: {
							sel: 'only',
						},
					})
					.then(res => {
						let { meta, data } = res.data
						if (meta.status != 200) {
							this.$message.error(meta.msg)
							return
						}
						this.staticList = data
					})
					.catch(err => {
						{
							console.log(err.message)
						}
					})
			}
		},
		// 切换tab栏触发函数
		beforeTab(activeName, oldActiveName) {
			if (oldActiveName == '0' && this.ruleForm.goods_cat.length != 3) {
				this.$message.error('请选择商品分类！')
				return false
			}
		},
		//级联选择框选中的事件
		handleChange(v) {
			if (v.length < 3) {
				this.ruleForm.goods_cat = []
				this.$message.error('不能选择第二级分类！')
				return
			}
		},
		// 获取数据
		getListData() {
			this.$http.get(`/categories`).then(res => {
				let { data, meta } = res.data
				if (meta.status != 200) {
					this.$message.error(meta.msg)
				}
				this.list = data
			})
		},
		// 获取级联选择器选中的商品数据
		getCategoriesData() {
			this.$http
				.get(`categories/${this.ruleForm.goods_cat[2]}/attributes`, {
					params: {
						sel: 'many',
					},
				})
				.then(res => {
					let { data, meta } = res.data
					if (meta.status != 200) {
						this.$message.error('获取参数失败！')
						return
					}
					data.forEach(item => {
						item.attr_vals =
							item.attr_vals.length == 0 ? [] : item.attr_vals.split(' ')
					})

					this.CategoriesData = data
				})
		},
	},
	created() {
		this.getListData()
	},
}
</script>

<style scoped>
.el-steps {
	text-align: left;
	margin: 15px 0;
	font-size: 12px;
}
.el-card {
	text-align: left;
	position: relative;
	overflow: none;
}
.previewImg {
	max-width: 100%;
	height: auto;
}
.btn-top {
	margin-top: 15px;
}
.mains{
	position: relative;
}
.btnBlack{
	position: absolute;
	right: 7%;
	z-index: 999;
	top: -85%;
}
</style>
